import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class OpenApiTokenGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    try {
      const request = context.switchToHttp().getRequest();
      const { token, timestamp } = request.headers;
      if (!token || !timestamp) {
        throw new HttpException(
          {
            statusCode: 401,
            message: '缺少必要参数',
          },
          HttpStatus.UNAUTHORIZED,
        );
      }
      if (Date.now() - Number(timestamp) > 60 * 1000 * 5)
        throw new HttpException(
          {
            statusCode: 401,
            message: '请求已超时',
          },
          HttpStatus.UNAUTHORIZED,
        );
      return true;
    } catch (err) {
      if (err.response) {
        throw new HttpException(err.response, err.status);
      } else
        throw new HttpException(
          {
            statusCode: 401,
            message: 'Unauthorized',
          },
          HttpStatus.UNAUTHORIZED,
        );
    }
  }
}
